package com.letv.app.ljodfh.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiongbull.jlog.JLog;
import com.letv.app.ljodfh.base.Cache;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.letv.app.ljodfh.R;
import com.letv.app.ljodfh.base.BaseActivity;
import com.letv.app.ljodfh.base.BaseFragment;
import com.letv.app.ljodfh.beans.FocusColumn;
import com.letv.app.ljodfh.http.AbsListNetCallback;
import com.letv.app.ljodfh.http.NetUtils;
import com.letv.app.ljodfh.ui.activities.AddColumnActivity;
import com.letv.app.ljodfh.ui.adapter.HomePagerAdapter;
import com.letv.app.ljodfh.ui.utils.IHomeNetCallBack;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.letv.app.ljodfh.ui.activities.AddColumnActivity.COLUMN_LIST;

/**
 * Created by Administrator on 2017/6/19 0019.
 */
public class HomeFragment extends BaseFragment {

    private final String ColumnUrl = "lztv/index.json";

    @BindView(R.id.home_tablay)
    protected SlidingTabLayout home_tablay;
    @BindView(R.id.home_content_vp)
    protected ViewPager home_content_vp;

    @BindView(R.id.home_top_lay_tab)
    protected ViewGroup tabLay;
    @BindView(R.id.home_content_ll)
    protected LinearLayout content_ll;
    @BindView(R.id.home_no_data_ct)
    protected CustomFontTextView no_data;
    private HomePagerAdapter homePagerAdapter;
    private ArrayList<FocusColumn> list, thisColumnList;
    public static final int REQUEST_CODE = 1;
    public static final String COLUMN_DATA = "column_data";
    private Gson gson;
    private List<FocusColumn> al_column;
    private List<FocusColumn> ot_column;
    private String playBackUrl, searchUrl, contributeUrl, topicUrl;
    public static int playBackChannelId, searchChannelId;

    private IHomeNetCallBack homeNetCallBack;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof IHomeNetCallBack) {
            homeNetCallBack = (IHomeNetCallBack) context;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getColumn();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        FragmentManager fm = getChildFragmentManager();
//        if (fm != null && homePagerAdapter != null) {
//            String n = OtherUtils.makeFragmentName(home_content_vp.getId(), home_content_vp.getCurrentItem());
//            Fragment f = fm.findFragmentByTag(n);
//            JLog.e("f=" + f);
//            if (f != null) {
//                ColumnBaseFragment cbf = (ColumnBaseFragment) f;
////                cbf.set
//            }
//        }
        ColumnBaseFragment cbf = getCurrentFragment();
        if (cbf != null) {
            cbf.setParentShowing(!hidden);
            cbf.onHiddenChanged(hidden);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//            topLay.setVisibility(View.GONE);
//            tabLay.setVisibility(View.GONE);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//            topLay.setVisibility(View.VISIBLE);
//            tabLay.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean hasShowPlayer() {
        BaseFragment bf = getCurrentFragment();
        return bf != null && bf.hasShowPlayer();
    }

    @OnClick(value = {R.id.home_no_data_ct})
    public void OnClick(View view) {
        switch (view.getId()) {
//            case R.id.home_search_iv:
//                Intent searchIntent = new Intent(getActivity(), SearchActivity.class);
//                startActivity(searchIntent);
//                break;
//            case R.id.home_look_back_tv:
//                Intent playBackIntent = new Intent(getActivity(), LookBackActivity.class);
//                if (!TextUtils.isEmpty(playBackUrl) && playBackUrl.endsWith(".json")) {
//                    playBackIntent.putExtra(BaseActivity.EX_URL, playBackUrl);
//                    startActivity(playBackIntent);
//                } else {
//                    toast("数据错误");
//                }
//                break;
            case R.id.home_no_data_ct:
                showProgress("数据正在加载中...");
                getColumn();
                break;
        }
    }

    @Override
    public void onDetach() {
        homeNetCallBack = null;
        super.onDetach();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        final int pos = data.getIntExtra(AddColumnActivity.SELECT_POS, 0);
        if (pos > 0) {
            refreshData(data);
            final int currentPos = home_content_vp.getCurrentItem();
            home_content_vp.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (currentPos != pos) {
                        home_content_vp.setCurrentItem(pos);
                    } else {
                        home_content_vp.setCurrentItem(currentPos);
                    }
                }
            }, 200);
        } else {
            refreshData(data);
        }
    }

    @Override
    public boolean onBackPressed() {
        ColumnBaseFragment f = getCurrentFragment();
        if (f != null && f.onBackPressed()) {
            return true;
        }
        return super.onBackPressed();
    }

    private Gson initGson() {
        if (gson == null) {
            gson = new Gson();
        }
        return gson;
    }

    private void getColumn() {
        NetUtils.getNetAdapter().getChannelArray(getOwnerName(), ColumnUrl, new AbsListNetCallback<FocusColumn>(null) {
            @Override
            public void onSuc(List<FocusColumn> fChannels) {
                JLog.e("" + fChannels);
                closeProgress();
                setDatass(fChannels);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                closeProgress();
                no_data.setVisibility(View.VISIBLE);
                content_ll.setVisibility(View.GONE);
            }
        });
    }

    private void setDatass(List<FocusColumn> fChannels) {
        if (ListUtils.isListValued(fChannels)) {
            content_ll.setVisibility(View.VISIBLE);
            no_data.setVisibility(View.GONE);
            Cache.getInstance().setfChannels(fChannels);
            for (int i = 0; i < fChannels.size(); i++) {
                FocusColumn column = fChannels.get(i);
                String channelType = column.getChannelType();
                if (channelType.equals("8")) { //搜索
                    searchUrl = column.getChannelUrl();
                    fChannels.remove(column);
                    searchChannelId = column.getChannelId();
                    i--;
                } else if (channelType.equals("9")) {//节目回看
                    playBackUrl = column.getChannelUrl();
                    if (homeNetCallBack != null) {
                        homeNetCallBack.setOtherUrls(IHomeNetCallBack.MODE_PLAYBACK, playBackUrl);
                    }
                    playBackChannelId = column.getChannelId();
                    fChannels.remove(column);
                    i--;
                } else if (channelType.equals("10")) {//投稿
                    contributeUrl = column.getChannelUrl();
                    BaseFragment.setRebllionUrl(contributeUrl);
                    BaseFragment.setRebllionChannelId(column.getChannelId());
                    fChannels.remove(column);
                    i--;
                } else if (channelType.equals("11")) {//专题
                    topicUrl = column.getChannelUrl();
                    BaseFragment.setTopicUrl(topicUrl);
                    BaseFragment.setTopicChannelId(column.getChannelId());
                    fChannels.remove(column);
                    i--;
                }

            }
//            List<FocusColumn> list = compareSaveData(fChannels);
            if (ListUtils.isListValued(fChannels)) {
                thisColumnList = new ArrayList<>();
                thisColumnList.addAll(fChannels);
                //初始化栏目ID
                String id = getCurrentColumnId(0);
                Cache.getInstance().setCurrentChannelId(id);
            }
            boolean b = true;
            int s = -1;
            if (homePagerAdapter == null) {
//                homePagerAdapter = new HomePagerAdapter(getChildFragmentManager(), list);
                homePagerAdapter = new HomePagerAdapter(getChildFragmentManager(), fChannels);
                setAdapterTopHeiht(true);
                home_content_vp.setAdapter(homePagerAdapter);
                home_content_vp.setOffscreenPageLimit(1);
                home_tablay.setViewPager(home_content_vp);
                s = homePagerAdapter.getCount();
            } else {
                s = homePagerAdapter.getCount();
                setAdapterTopHeiht(true);
                homePagerAdapter.setData(list);
                b = s != homePagerAdapter.getCount();
            }

//            JLog.e("uuju  will to refresh column  b="+b+"   s="+s);
            refreshColumnTab(b);

        } else {
            no_data.setVisibility(View.VISIBLE);
            content_ll.setVisibility(View.GONE);
        }

        /**
         * 监听栏目切换
         */
        home_tablay.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                String id = getCurrentColumnId(position);
                Cache.getInstance().setCurrentChannelId(id);
            }

            @Override
            public void onTabReselect(int position) {
                String id = getCurrentColumnId(position);
                Cache.getInstance().setCurrentChannelId(id);
            }
        });
    }


    public String getCurrentColumnId(int position) {
        if (!ListUtils.isListValued(thisColumnList)) {
            return "";
        } else {
            return "" + thisColumnList.get(position).getChannelId();
        }

    }

    private ColumnBaseFragment getCurrentFragment() {
        if (home_content_vp == null || homePagerAdapter == null || homePagerAdapter.getCount() == 0) {
            return null;
        }
        ColumnBaseFragment cbf = homePagerAdapter.getFragmentByPos(home_content_vp.getCurrentItem());
        JLog.e("ffsf " + cbf);
        return cbf;
    }

    private void refreshData(Intent data) {
        ArrayList<FocusColumn> al_data = (ArrayList<FocusColumn>) data.getSerializableExtra(AddColumnActivity.COLUMN);
        for (int i = 0; i < al_data.size(); i++) {
            if (!al_data.get(i).isChoice()) {
                al_data.remove(i);
                i--;
            }
        }
        if (al_data.size() != 0) {
            if (homePagerAdapter != null) {
                int s = homePagerAdapter.getCount();
                homePagerAdapter.setData(al_data);
                home_tablay.notifyDataSetChanged();
//                JLog.e("===  will refresh data   " + homePagerAdapter.getCount()+"   s="+s);
                refreshColumnTab(s != homePagerAdapter.getCount());
            }

        }
    }

    private void refreshColumnTab(boolean b) {
        int size = homePagerAdapter.getCount();
        if (size == 0 || !b) {
            return;
        }
//        JLog.e("uuju   in refresh size="+size+"   "+home_tablay.getWidth());
//        JLog.e("uuju  " + getResources().getDimension(R.dimen.tab_home_padding_m)
//                + "   " + getResources().getDimensionPixelOffset(R.dimen.tab_home_padding_m)
//                + "   " + getResources().getDimensionPixelSize(R.dimen.tab_home_padding_m) +
//                "\n   " + DensityUtil.dip2px(getContext(), 8) + "   " + DensityUtil.dip2px(getContext(), 12));
        if (size == 6) {
//            home_tablay.setTabSpaceEqual(true);
            home_tablay.notifyDataSetChanged();
        } else {
//            home_tablay.setTabSpaceEqual(false);
            float d = getResources().getDimension(R.dimen.tab_home_padding_m);
            if (size < 7) {
                d = getResources().getDimension(R.dimen.tab_home_padding);
            }
            home_tablay.setTabPaddingPx(getResources().getDimension(R.dimen.tab_home_padding_m));
            home_tablay.notifyDataSetChanged();
        }
    }

    private void setAdapterTopHeiht(boolean isNewInstance) {
        if (isNewInstance) {
            tabLay.postDelayed(new Runnable() {
                @Override
                public void run() {
                    homePagerAdapter.setTopHeight(othersHeight + tabLay.getHeight());
                }
            }, 500);
        } else {
            homePagerAdapter.setTopHeight(othersHeight + tabLay.getHeight());
        }
    }

    public int getCurrentSelectedIndex() {
        return home_content_vp.getCurrentItem();
    }

    public void setCurrentSelectIndex() {
        int pos = homePagerAdapter.getPosCurrentPage(String.valueOf(HomePagerAdapter.TYPE_NEWS));
        if (pos > 0) {
            home_content_vp.setCurrentItem(pos);
        }

    }

    private List<FocusColumn> compareSaveData2(List<FocusColumn> netList) {
        al_column = netList;
        if (netList.size() <= 6) {
//            add_column.setVisibility(View.GONE);
            return netList;
        } else {
            String param = (String) SharedPreferencesUtil.getParam(getActivity(), COLUMN_LIST, "[]");
            ArrayList<String> selectIds = initGson().fromJson(param, new TypeToken<ArrayList<String>>() {
            }.getType());
            JLog.e("qwer   selectids=" + selectIds);
            if (ot_column == null) {
                ot_column = new ArrayList<>();
            } else {
                ot_column.clear();
            }
            ArrayList<String> idsTemp = new ArrayList<>(selectIds);
            ArrayList<FocusColumn> list = new ArrayList<>();
            String id = null;
            if (idsTemp.size() == 1) {
                id = idsTemp.get(0);
            }
            for (int i = 0; i < netList.size(); i++) {
                if (i < 6) {
                    list.add(netList.get(i));
                } else {
                    FocusColumn fc = netList.get(i);
                    ot_column.add(fc);
                    if (!TextUtils.isEmpty(id)) {
//                        if (TextUtils.equals(fc.getChannelId(),id)){
//
//                        }
                    } else {
                        if (idsTemp.size() > 0) {
                            for (int j = 0; j < idsTemp.size(); j++) {
                            }
                        }
                    }
                }
            }
            for (int i = 0; i < selectIds.size(); i++) {

            }

            return list;
        }
    }

    /**
     * 与本地保存的数据相比较看那些数据是已经保存的
     *
     * @param netList
     * @return
     */
    private List<FocusColumn> compareSaveData(List<FocusColumn> netList) {
        ArrayList<FocusColumn> saveList = new ArrayList<>();
        String param = (String) SharedPreferencesUtil.getParam(getActivity(), COLUMN_LIST, "");
        if (!TextUtils.isEmpty(param)) {
            ArrayList<FocusColumn> focusColumns = initGson().fromJson(param, new TypeToken<ArrayList<FocusColumn>>() {
            }.getType());
            for (FocusColumn netColumn : netList) {
                int channelId = netColumn.getChannelId();
                for (int i = 0; i < focusColumns.size(); i++) {
                    if (channelId == focusColumns.get(i).getChannelId()) {
                        netColumn.setChoice(focusColumns.get(i).isChoice());
                    }
                }
                if (netColumn.isChoice()) {
                    saveList.add(netColumn);
                }
            }
            al_column = netList;
            String s = initGson().toJson(al_column);
            SharedPreferencesUtil.setParam(getActivity(), AddColumnActivity.COLUMN_LIST, s);
            if (ListUtils.isListValued(saveList)) {
                return saveList;
            } else {
                return noSaveColumn(netList);
            }
        } else {
            return noSaveColumn(netList);
        }
    }


    private ArrayList<FocusColumn> noSaveColumn(List<FocusColumn> netList) {
        al_column = netList;
        list = new ArrayList<>();
        if (netList.size() > 6) {
//            add_column.setVisibility(View.VISIBLE);
            for (int i = 0; i < 6; i++) {
                list.add(netList.get(i));
                al_column.get(i).setChoice(true);
            }
        } else {
//            add_column.setVisibility(View.GONE);
            list.addAll(netList);
            for (FocusColumn column : al_column) {
                column.setChoice(true);
            }
        }
        String s = initGson().toJson(al_column);
        SharedPreferencesUtil.setParam(getActivity(), AddColumnActivity.COLUMN_LIST, s);
        return list;
    }
}
